import { message } from "antd";
import axios from "axios";
import React from "react";
import { Url } from "../url";
import { Table, Tag, Space, Divider, Button, Modal } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';

const { confirm } = Modal;

export class NewsManagement extends React.Component {

    state = {
        newsList: []
    }

    componentDidMount = () => {

        this.getNewsList();

    }

    getNewsList = () => {
        axios.get(Url.newsAll).then(
            (response) => {
                this.setState({
                    newsList: [...response.data]
                });
            })
            .catch((error) => {
                message.error("Network Error");
            });
    }


    columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            key: 'id',
            render: text => <div style={{ color: "darkblue" }}>{text}</div>,
        },
        {
            title: 'News Title',
            dataIndex: 'title',
            key: 'title',
        },
        {
            title: 'Author',
            dataIndex: 'author',
            key: 'author',
        },
        {
            title: 'Edit Time',
            dataIndex: 'editTime',
            key: 'editTime',
            render: text => <div>{(new Date(text)).toLocaleDateString() + " " + (new Date(text)).toLocaleTimeString()}</div>,
        },
        {
            title: 'Action',
            key: 'action',
            render: (text, record) => (
                <Space size="middle">
                    <a href={"/#/admin/news/" + record.id}>View</a>
                    <Divider type="vertical" />
                    <Button type="link" danger onClick={() => {
                        this.deleteNews(record.id, record.title);
                    }}>Delete</Button>
                </Space>
            ),
        },
    ];

    deleteNews = (id, title) => {

        confirm({
            title: 'Are you sure delete this news?',
            icon: <ExclamationCircleOutlined />,
            content: 'Title: ' + title,
            okText: 'Yes',
            okType: 'danger',
            cancelText: 'No',
            onOk: () => {
                axios.get(Url.deleteNews + id).then(
                    (response) => {
                        this.getNewsList();
                        message.success("Delete successfully.");
                    }
                ).catch((error) => {
                    message.error("Network Error");
                    console.log(error);
                });
            },
            onCancel() {
            },
        });
    }

    render = () => {
        return <div style={{ width: "75vw", minHeight: "100%" }}>
            <Table columns={this.columns} dataSource={this.state.newsList} />
        </div>
    }

}